/**
 * 
 */
package com.ph.shopping.facade.merchant.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.facade.agent.entity.Agent;
import com.ph.shopping.facade.agent.service.IAgentService;
import com.ph.shopping.facade.agent.vo.AgentVo;
import com.ph.shopping.facade.mapper.MerchantChargeRecordMapper;
import com.ph.shopping.facade.mapper.MerchantDrawcashRecordMapper;
import com.ph.shopping.facade.mapper.MerchantMapper;
import com.ph.shopping.facade.mapper.PositionMapper;
import com.ph.shopping.facade.member.service.ISmsCodeSendService;
import com.ph.shopping.facade.merchant.entity.Merchant;
import com.ph.shopping.facade.merchant.entity.MerchantChargeRecord;
import com.ph.shopping.facade.merchant.entity.MerchantDrawcashRecord;
import com.ph.shopping.facade.merchant.entity.MerchantImage;
import com.ph.shopping.facade.merchant.entity.Position;
import com.ph.shopping.facade.merchant.entity.UserBalance;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.vo.CommunityVo;
import com.ph.shopping.facade.merchant.vo.MerchantDetaileVo;
import com.ph.shopping.facade.merchant.vo.PositionVo;
import com.ph.shopping.facade.merchant.vo.UserBalanceRecordVo;
import com.ph.shopping.facade.permission.dto.UserRoleDto;
import com.ph.shopping.facade.permission.entity.User;
import com.ph.shopping.facade.permission.service.IUserService;

/**
 * @项目：phshopping-service-merchant
 *
 * @描述：商户接口实现
 *
 * @作者：huangdd
 *
 * @创建时间：2017年3月10日
 *
 * @Copyright @2017 by huangdd
 */
@Component
@Service(version="1.0.0")
public class MerchantService extends BaseService implements IMerchantService{
    @Autowired
    MerchantMapper merchantMapper;
    
    @Autowired
    PositionMapper positionMapper;

	//商户充值记录
	@Autowired
	private MerchantChargeRecordMapper merchantChargeRecord;

	//商户提现记录
	@Autowired
	private MerchantDrawcashRecordMapper merchantDrawcashRecordMapper;
	
    @Reference(version="1.0.0")
    private IUserService iUserService;
    
    @Reference(version="1.0.0")
    private IAgentService iAgentService;

     //发送短信接口
	 @Reference(version="1.0.0",timeout=30000)
	 private ISmsCodeSendService smsCodeSendService;


	/**
	 * 生成随机密码
	 * 
	 * @return
	 */
	public static String getSmsCode() {
		return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
	}
	
    /**
     * 商户列表
     * @return
     */
    @Override
    public Result getMerchantList(Merchant merchant,PageBean pagebean) {
    	try {
    		PageHelper.startPage(pagebean.getPageNum(), pagebean.getPageSize());
    		List<MerchantDetaileVo> merchantList = merchantMapper.getMerchantList(merchant);
    		if(merchantList == null || merchantList.size() < 0){
    			logger.debug("无商户数据");
    			return getResult(ResultEnum.NO_MERCHANDATA_EXCEPTION);
    		}
    		PageInfo<MerchantDetaileVo>pageInfo=new PageInfo<MerchantDetaileVo>(merchantList);
    		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
    	}catch (Exception e) {
			logger.error("获取商户列表异常!");
			e.printStackTrace();
			return getResult(ResultEnum.SELECT_MRRCHANT_EXCEPTION);
		}     
    }

    /**
     * 新增商户和商户图片
     */
    @Override
    @Transactional(rollbackFor=BizException.class)
    public Result addMerchant(Merchant merchant,List<MerchantImage>  list) throws BizException {
    	
    	Long deleteUserId = 0l;//用于商户新增失败时，回滚用户新增的操作
    	Result result = getResult(ResultEnum.SUCCESS); 
    	try {
    		//通过townId查询此条数据 差position表 唯一条数据放入merchant表
	        Position position = positionMapper.getPositionById(merchant.getTownId());//唯一数据
	        merchant.setProvinceId(position.getProvinceId());
	        merchant.setCityId(position.getCityId());
	        merchant.setCountyId(position.getCountyId());
	        merchant.setTownId(position.getTownId());
	        
	    	//得到代理id
	        Agent agent = new Agent();
	        agent.setProvinceId(merchant.getProvinceId());
	        agent.setCityId(merchant.getCityId());
	        agent.setCountyId(merchant.getCountyId());
	        agent.setTownId(merchant.getTownId());
	        agent.setAgentLevelId(new Long(3));//社区的等级是3
	        AgentVo agentByArea = iAgentService.getAgentByArea(agent);
	        if(agentByArea!=null){
		        merchant.setAgentId(agentByArea.getId());
	        }

			//1.新增一个用户,=得到用户id 此id作为商户表主键 关联商户表 商户图片表
	        UserRoleDto dto = new UserRoleDto();
	        dto.setTelphone(merchant.getMerchantTel());
	        dto.setRoleCode(RoleEnum.MERCHANT.getCode());//设置为商户类型
	        Result userResult = iUserService.addUser(dto);//新增用户,调用用户接口
	        
	        //调用用户接口后，判断1.result是否为空;2.返回的Code是否为“用户已注册”;3.判断是否返回成功Code
	        if (null != result&& !ResultEnum.REGISTERED.getCode().equals(userResult.getCode())
	        		&& ResultEnum.SUCCESS.getCode().equals(userResult.getCode())){

		        Long userId = (Long) userResult.getData();//返回的Id
		        deleteUserId = userId;//用于商户新增失败时，回滚用户新增的操作
		        
		    	//新增商户
		        merchant.setId(userId);
		        merchantMapper.addMerchant(merchant);//新增商户默认状态为待审核
		        
		        //新增商户的余额账户默认给他余额设置为0  ph_user_balance
		        int addMerchantBalance = merchantMapper.addMerchantBalance(merchant);
		        if(addMerchantBalance !=1){
		        	logger.error("新增商户账户余额(新增商户时默认添加)异常");
		        	return getResult(ResultEnum.ADD_MERCHANT_BALANCE_EXCEPTION);
		        }
		        //新增商户图片
		        for(MerchantImage m : list){
		        	m.setMerchantId(merchant.getId());
		        }
		        if(list.size()!=0){
			        merchantMapper.addMerchantImage(list);
		        }
		     
	        } else{
	        	result.setCode(userResult.getCode());
	        	result.setMessage(userResult.getMessage());
	        }
    	} catch (Exception e) {
    		//如果商户新增失败了，删除用户
			 User userDelete = new User();
			 userDelete.setId(deleteUserId);
			iUserService.deleteUser(userDelete);
			e.printStackTrace();
			logger.error("商户新增异常:" + e.getMessage());
			result = getResult(ResultEnum.ADD_MRRCHANT_EXCEPTION);
			throw new BizException("商户新增异常:60001");
		}
    	return result;
    }
     /**
      * 修改商户
      */
    @Override
    @Transactional(rollbackFor=BizException.class)
    public Result updateMerchant(Merchant merchant,List<MerchantImage>  list) throws BizException{
    	Result result = getResult(ResultEnum.SUCCESS); 
    	try {		
	    	//得到代理id (区域不能改变那么通过区域获取的代理也不会变)
//	        Agent agent = new Agent();
//	        agent.setProvinceId(merchant.getProvinceId());
//	        agent.setCityId(merchant.getCityId());
//	        agent.setCountyId(merchant.getCountyId());
//	        agent.setCommunityId(merchant.getTownId());
//	        agent.setAgentLevelId(new Long(3));//社区的等级是3
//	        AgentVo agentByArea = iAgentService.getAgentByArea(agent);
//	        merchant.setAgentId(agentByArea.getId());
	        //修改商户表
	        merchant.setUpdateTime(new Date());//给一个修改时间
	        merchant.setPositionId(merchant.getTownId());//跟新增一样把townId的值赋给positionId
	        
	        
    		merchantMapper.updateByPrimaryKeySelective(merchant);
    		//删除此商户的图片
    		merchantMapper.deteleMerchantImage(merchant.getId());
	        //新增商户图片
	        for(MerchantImage m : list){
        	m.setMerchantId(merchant.getId());
	        }
	        merchantMapper.addMerchantImage(list);
    	} catch (Exception e) {
			e.printStackTrace();
			logger.error("修改商户异常!:" + e.getMessage());
			result = getResult(ResultEnum.UPDATE_MRRCHANT_EXCEPTION);
			throw new BizException("修改商户异常:60002");
		}
    	return result;
    }
    /**
     * 商户详细
     * @return
     */
    @Override
    public Result detaileMerchant(Merchant merchant){
    	try {
	    	MerchantDetaileVo detaileMerchant = merchantMapper.detaileMerchant(merchant);
	    	if(detaileMerchant!=null){
		    	Map<String,Object> map = new HashMap<String,Object>();
		    	map.put("id", merchant.getId());
		    	map.put("type", 1);
		    	detaileMerchant.setBusinesslicenseImages(merchantMapper.merchantImageByMerchantID(map));
		    	map.put("type", 2);
		    	detaileMerchant.setIdCardImages(merchantMapper.merchantImageByMerchantID(map));
		    	map.put("type", 3);
		    	detaileMerchant.setShopImages(merchantMapper.merchantImageByMerchantID(map));
	    	}
	    	return getResult(ResultEnum.SUCCESS, detaileMerchant);
    	}catch (Exception e) {
			logger.error("获取商户详细异常!");
			e.printStackTrace();
			return getResult(ResultEnum.DETAILE_MRRCHANT_EXCEPTION);
		} 
    }
   /**
 	 * 获取所有的省市县区 通过 ph_area areaId
 	 */
	@Override
     public  Result  getAllPosition(String pid){
    	 try {
    		 return getResult(ResultEnum.SUCCESS, merchantMapper.getAllPosition(pid));
    	 }catch (Exception e) {
 			logger.error("获取省市区位置异常!");
 			e.printStackTrace();
 			return getResult(ResultEnum.SELECT_POSITION_EXCEPTION);
 		}
     };
     /**
      * 修改商户状态
      * @param id
      * @return
      */
     @Override
     public Result updateMerchatStatues(Merchant merchant){
    	 Result result = getResult(ResultEnum.SUCCESS);
         try{
             //1.冻结或者解冻账号
             if(3==merchant.getStatus()||1==merchant.getStatus()){
                 User user = new User();
                 user.setId(merchant.getId());
                 if(merchant.getStatus() == 3){
                     logger.debug("商户冻结");
                     user.setIsable(Byte.decode(CommonConstants.USER_ISABLE_NO));
                 }else{

                 	if(merchant.getStatus()==1){
                 		
                         //解冻或者审批时更新密码并发送短信
                         //除了管理员类型的账号以外，需要随机生成密码
         	        	String pass = getSmsCode();
         	        	User userPass = new User();
         	        	userPass.setPassword(MD5.getMD5Str(pass));
         	        	userPass.setId(merchant.getId());
         	        	iUserService.updatePassword(userPass);
                     	
                     	//通过短息的形式发送密码给用户
                         if (!sendMessage(merchant.getMerchantTel(), SmsCodeType.SEND_USER_PWD.getCodeType(), pass))
                         	throw new BizException("给用户发送密码短信接口异常:7071");
                 	} 
                	 
                     logger.debug("商户解冻");
                     user.setIsable(Byte.decode(CommonConstants.USER_ISABLE_YES));
                 }
                 iUserService.frozenOrEnableUser(user);
             }
             //2.设置商户表状态
             merchantMapper.updateByPrimaryKeySelective(merchant);

         } catch (Exception e) {
             e.printStackTrace();
             if("3".equals(merchant.getStatus())){
                 logger.error("商户冻结异常:" + e.getMessage());
                 result = getResult(ResultEnum.UPDATE_MERCHANT_STATUES_EXCEPTION);
                 throw new BizException("商户冻结异常:60011");
             }else{
                 logger.error("商户解冻异常:" + e.getMessage());
                 result = getResult(ResultEnum.UPDATE_MERCHANT_STATUES_EXCEPTION);
                 throw new BizException("商户解冻异常:60011");
             }
         }
         return result;
     };
     /**
      * 修改商户 用于回填
      */
     @Override
      public Result getMerchantDetailForUpdate(Merchant merchant){
		 try {
			 MerchantDetaileVo merchantDetaileVo = merchantMapper.getMerchantDetailForUpdate(merchant);
	    	Map<String,Object> map = new HashMap<String,Object>();
	    	map.put("id", merchant.getId());
	    	map.put("type", 1);
	    	merchantDetaileVo.setBusinesslicenseImages(merchantMapper.merchantImageByMerchantID(map));
	    	map.put("type", 2);
	    	merchantDetaileVo.setIdCardImages(merchantMapper.merchantImageByMerchantID(map));
	    	map.put("type", 3);
	    	merchantDetaileVo.setShopImages(merchantMapper.merchantImageByMerchantID(map));
	    	return getResult(ResultEnum.SUCCESS, merchantDetaileVo);
    	 }catch (Exception e) {
 			logger.error("获取商户异常!");
 			e.printStackTrace();
 			return getResult(ResultEnum.DETAILE_MRRCHANT_EXCEPTION);
 		}
      };
      
      

      //发送短信接口
      private boolean sendMessage(String phone,String type,String message) {
      	logger.info("短信发送接口入参,phone={},type={}",phone,type);
      	Result result = smsCodeSendService.sendSmsCodeByCustomMsg(phone, type, message);
      	logger.info("短信发送接口返回值,result={}",JSON.toJSONString(result));
      	if (null != result && ResultEnum.SUCCESS.getCode().equals(result.getCode())) return true;
      	return false;
      }
      /**
       * 查询商户或者供应商或者代理商的余额(提供给其他小组用)
       */
      public Result getUserBalance(UserBalance userBalance){
    	  try {
	    	  UserBalance ub = merchantMapper.getUserBalance(userBalance);
	    	  if(ub == null){
	    		  return getResult(ResultEnum.NO_USER_BALANCE_RECORD_EXCEPTION);
	    	  }
	    	  return  getResult(ResultEnum.SUCCESS, ub);
    	  }catch (Exception e) {
   			logger.error("获取用户余额记录异常!");
   			e.printStackTrace();
   			return getResult(ResultEnum.USER_BALANCE_RECORD_EXCEPTION);
   		}
      }; 
      
      /**
       * 根据商户的id 返回该商户的市级代理(其他小组用)
       */
      public  Result getCityAgentByMerchant(Merchant merchant0){
    	  try {
	    	  Merchant merchant = merchantMapper.getMerchantById(merchant0);
	    	  if(merchant == null){
	    		  logger.error("无此商户的数据");
	    		  return getResult(ResultEnum.NO_MERCHANT_EXCEPTION);
	    	  }
	    	  Agent agent = new Agent();
	    	  agent.setCountyId(merchant.getCountyId());
	    	  agent.setCityId(merchant.getCityId());
	    	  agent.setProvinceId(merchant.getProvinceId());
	    	  //获取代理
	    	  AgentVo agentVo = iAgentService.getCityAgentByArea(agent);
	    	  if(agentVo == null){
	    		  logger.error("无此商户的代理数据");
	    		  return getResult(ResultEnum.GET_AGENT_BY_MERCHANT);
	    	  }
	    	  return  getResult(ResultEnum.SUCCESS, agentVo);
    	  }catch (Exception e) {
     			logger.error("通过商户获取代理异常!");
     			e.printStackTrace();
     			return  getResult(ResultEnum.GET_AGENT_BY_MERCHANT);
     		}
      };
      
    /**
     * 获取商户的余额记录流水
	  * @param userBalance 商户余额记录
	  * @return List<BalanceRecordVo> 商户余额记录集合
	  * @throws BizException
	  * @author liuy
     */
	@Override
	public Result getUserBalanceRecordVoList(@ModelAttribute PageBean page,@ModelAttribute  UserBalanceRecordVo userBalanceRecordVo) throws BizException {
		//备注：余额记录的来源有：充值、现金支付（线下订单）、供应链订单        线上积分支付、线下积分支付、线上订单（商户和代理商不涉及）

		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<UserBalanceRecordVo> list= merchantMapper.getUserBalanceRecordVoList(userBalanceRecordVo);
	    PageInfo<UserBalanceRecordVo> pageInfo=new PageInfo<UserBalanceRecordVo>(list);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
	}
	

    /**
     * 新增商户充值记录
     * @param merchantChargeRecord 商户充值记录
     * @return Result
     */
	@Override
	public Result addMerchantChargeRecord(MerchantChargeRecord merchantChargeRecord) throws Exception {
		this.merchantChargeRecord.addMerchantChargeRecord(merchantChargeRecord);
		return  getResult(ResultEnum.SUCCESS);
	}
	
    /**
     * 新增商户提现记录
     * @param merchantDrawcashRecord 商户提现记录
     * @return Result
     */
	@Override
	public Result addMerchantDrawcashRecord(MerchantDrawcashRecord merchantDrawcashRecord) throws Exception {
		this.merchantDrawcashRecordMapper.addMerchantDrawcashRecord(merchantDrawcashRecord);
		return  getResult(ResultEnum.SUCCESS);
	}
	
 	/**
      * 查询登陆人当天的已提现总额
      * @param merchantDrawcashRecord 商户提现记录
      * @return Result
      * @author 刘颖
      */
	@Override
	public BigDecimal getDrawcashMoneyToday(MerchantDrawcashRecord merchantDrawcashRecord) throws Exception {
		return this.merchantDrawcashRecordMapper.getDrawcashMoneyToday(merchantDrawcashRecord);
	}
	
	   /**
     * 区域
     * @param id
     * @param type
     * @return
     */
    public Result getPositionByIdAndType(String id, String type){
    	List<PositionVo> list = null;
		if(type.equals("0")){
			list = this.positionMapper.getPosition();
		}
		if(type.equals("1")){
			list = this.positionMapper.getCityByPid(Long.valueOf(id));
		}
		if(type.equals("2")){
			list = this.positionMapper.getCountyByCid(Long.valueOf(id));
		}
		if(type.equals("3")){
			list = this.positionMapper.getTownByCid(Long.valueOf(id));
		}
    	return getResult(ResultEnum.SUCCESS, list) ;
    }
    
 	/**
      * 查询登陆人提现待审核记录
      * @param merchantDrawcashRecord 商户提现记录
      * @return Result
      * @author 刘颖
      */
	@Override
	public BigDecimal getDrawcashStatusPendingTotal(MerchantDrawcashRecord merchantDrawcashRecord) throws Exception {
		return this.merchantDrawcashRecordMapper.getDrawcashStatusPendingTotal(merchantDrawcashRecord);
	};
	
    /**
     * 通过主键获取区域
     * @param id
     * @return
     */
    public Position getPositionById(Long id){
    	Position position1 = positionMapper.getPositionById(id);
    	return position1;
    };
}
